Functions in Swift

Posted on 18 May, 2018 in Swift

Hello there,

Functions

Functions with no return value and no parameters

We use functions to generalize specific types of codes. Let's consider following example.

// We define a function here.
func printHello() {
  print("Hello there, General Kenobi")
}

// Now we need to call our function.
printHello() // It will print "Hello there, General Kenobi"

As we can see here, we need to define the function, then use it.

Functions with parameters

// We define a function here with a parameter.
func printHello(name: String) {
  print("Hello there, General \(name)")
}

// Now we need to call our function.
printHello(name: "Kenobi") // It will print "Hello there, General Kenobi"
printHello(name: "Anakin") // It will print "Hello there, General Anakin"

Swift has brilliant function parameter system. If we define the function as in the function one need to use printHello(name: "Kenobi") for the function call. We have an underscore inside the function parameter in function two. It allows us to not to use parameter name. therefore, we use printHello("Kenobi"). finally we have withName tag inside the function function three. We call it by using printHello(withName: "Kenobi").

// function one
// We define a function here with a parameter.
func printHello(name: String) {
  print("Hello there, General \(name)")
}

// function two
// We define a function here with a parameter using underscore.
func printHello(_ name: String) {
  print("Hello there, General \(name)")
}

// function three
// We define a function here with a parameter using .
func printHello(withName name: String) {
  print("Hello there, General \(name)")
}

We can combine the function parameter system.

func printHello(withName name: String, _ surname: String , age: Int) {
  print("Hello there, General \(name) \(surname) - (Your age is \(age))")
}
printHello(withName: "Kenobi", "IDK", age: 30)

Functions with parameters and return value

Let's dive in the example

func ageCalculator(withBirthdayYear BdYear: Int, _ currentYear: Int) -> Int {
  return currentYear - BdYear
}
// Assigning the return value to the variable called jakesAge
let jakesAge = ageCalculator(withBirthdayYear: 1993, 2018)
print("Jake your age is \(jakesAge)")

Closures

Let us consider following example. We will building .sort(by: ) function. We need to implement Foundation for using that function

func sortOrder(_ numberOne : Int, _  numberTwo : Int) -> Bool {
  return numberOne < numberTwo
}

let sortedArray = [3,4,2,5,6,1,7].sorted(by: sortOrder)

sorted(by:) function takes a function argument. The function has 2 given parameters and boolean return value. We can define our closure in this way. However, there are better ways to type these. Let's look at them.

// Instead of defining a function outside just for this sort function. We shall use closures to represent our function.
let sortedArray = [3,4,2,5,6,1,7].sorted(by: { (_ numberOne: Int, _ numberTwo: Int) -> Bool in
    return numberOne < numberTwo
  })

We made a huge mile stone by using closure instead of function. Nevertheless, we one clear way to represent our closure.

// Swift knows that array contains integers. Therefore, we do not need to specify types of numberOne and numberTwo
// Swift also knows that sorted(by: ) takes argument as (Integer, Integer) -> Bool. Therefore we don't need to type return value
// Swift allows us to use $0, $1, $2 ... for representing variables
let sortedArray = [3,4,2,5,6,1,7].sorted(by: {$0 < $1})

Escaping

This topic is entertaining to implement. We allow a function to have different endings.

// Escaping allows us to continue from there in somewhere else
func ageCalculator(withBirthdayYear BdYear: Int, _ currentYear: Int, returnFunction: @escaping (Int) -> ()) {
  returnFunction(currentYear - BdYear)
}

// In here we calculated returnedAge and continued from here.
ageCalculator(withBirthdayYear: 1996, 2018) { (returnedAge) in
  print("This age is came from another function. Plus your age is \(returnedAge)")
}

// This is another function for closures
ageCalculator(withBirthdayYear: 2013, 2018) { (returnedAge) in
  print("I feel young. However, my age is (returnedAge)")
}

Some exercises

This exercise is taken from here. You can find more code examples in that repository, that I have covered in the iOS lecture.

  1. Create a function that takes 2 double numbers and returns their sum

We will solve those question. However, I highly recommend you to solve the question first. Instead of looking the solutions first.

Solutions

One

func sumDoubles(withNumberOne nOne: Double, _ nTwo: Double) -> Double {
  return nOne + nTwo
}